/**
 * 
 */
package com.archives.blog.web.erp;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.EnumUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.archives.blog.common.domain.entity.Admin;
import com.archives.blog.common.domain.pojo.request.AdminLoginRequest;
import com.archives.blog.common.domain.pojo.result.Result;
import com.archives.blog.common.utils.SessionUtil;
import com.archives.blog.manager.AdminManager;
import com.archives.blog.web.BaseSupportController;
import com.archives.blog.web.routers.ErpRouters;

/**
 * 后台首页
 * 
 * @author chh
 *
 */
@Controller
public class HomeController extends BaseSupportController{

	/** 日志管理*/
	private static Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * 管理员管理
	 */
	@Autowired
	private AdminManager adminManager;
	
	/**
	 * 路由入口
	 * 
	 * @return
	 */
	@RequestMapping("/erp/{templateName}")
	String erpRouters(ModelMap model, @PathVariable String templateName){
		try {
			ErpRouters router = EnumUtils.getEnum(ErpRouters.class, templateName);
			if (router == null) {
				router = ErpRouters.index;
			} else if (router.equals(ErpRouters.login)){
				return router.getPath();
			}
			model.addAttribute("router_view", router);
		} catch (Exception e) {
			logger.error("路由跳转异常", e);
			model.addAttribute("router_view", ErpRouters.error);
		}
		return "/erp/index";
	}

	/**
	 * 用户登录
	 * 
	 * @param req 
	 * @param request
	 * @param res
	 * @return
	 */
	@RequestMapping(value = "/erp/login", method = RequestMethod.POST)
	@ResponseBody
	public Result<Admin> login(HttpServletRequest req, @Valid @RequestBody AdminLoginRequest request, BindingResult res){
		Result<Admin> result = new Result<Admin>();
		try {
			Admin admin = adminManager.login(request);
			result.setResultObject(admin);
			result.setSuccess(true);
			SessionUtil.putAdminToSession(req, admin);
		} catch (Exception e) {
			result.setErrorMsg(e.getMessage());
			logger.error("用户登录异常", e);
		}
		return result;
	}
}
